<?php
// +----------------------------------------------------------------------
// | Yzncms [ 御宅男工作室 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2007 http://yzncms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 御宅男 <530765310@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller\auth;

use app\admin\model\AdminUser as Admin_User;
use app\admin\model\AuthGroup as AuthGroupModel;
use app\common\controller\Adminbase;
use think\Db;
use util\Tree;

/**
 * 分公司账号管理
 */
class Manager2 extends Adminbase
{
    protected $searchFields = 'id,username,nickname';
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];

    protected function initialize()
    {
        parent::initialize();
        $this->modelClass = new Admin_User;
    }

    /**
     * 管理员管理列表
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($page, $limit, $where, $sort, $order) = $this->buildTableParames();
            $list = $this->modelClass
                ->where($where)
                ->where('roleid', '=', 3)
                ->where('is_del', '=', 0)
                ->field(['password', 'salt', 'token'], true)
                ->order($sort, $order)
                ->append(['area_name'])
                ->paginate($limit);
            $result = ["code" => 0, 'count' => $list->total(), "data" => $list->items()];
            return json($result);
        }
        return $this->fetch();
    }

    /**
     * 添加管理员
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post('');
            $params['roleid'] = 3;
            $result = $this->validate($params, 'AdminUser.insert');
            $passwordinfo = encrypt_password($params['password']); //对密码进行处理
            $params['password'] = $passwordinfo['password'];
            $params['encrypt'] = $passwordinfo['encrypt'];
            if (true !== $result) {
                return $this->error($result);
            }
//            if (!in_array($params['roleid'], $this->childrenGroupIds)) {
//                $this->error('没有权限操作！');
//            }
            try {
                Db::name('area')->update(['is_agent' => 1, 'id' => $params['area_id']]);
                $this->modelClass->save($params);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success("添加成功！", url('index'));
        }
        //获取山东省所有市区
        $cityWhere[] = ['pid', '=', 370000];
        $cityWhere[] = ['is_agent', '=', 0];
        $cityList = Db::name('area')->where($cityWhere)->select();
        foreach ($cityList as $k => $v) {
            $cityList[$v['id']] = $v['name'];
            unset($cityList[$k]);
        }
        $this->assign('cityList', $cityList);
        return $this->fetch();
    }

    /**
     * 管理员编辑
     */
    public function edit()
    {
        $id = $this->request->param('id/d', 0);
        $row = $this->modelClass->get($id);
        if (!$row) {
            $this->error('记录未找到');
        }
//        if (!in_array($row->id, $this->childrenAdminIds)) {
//            $this->error('没有权限操作！');
//        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post('');
            $params['roleid'] = 3;
            if ($params['old_area'] != $params['area_id']) {
                $update_data1 = array(
                    'id' => $params['old_area'],
                    'is_agent' => 0
                );
                $update_data2 = array(
                    'id' => $params['area_id'],
                    'is_agent' => 1
                );
                Db::name('area')->update($update_data1);
                Db::name('area')->update($update_data2);
            }

            $result = $this->validate($params, 'AdminUser.update');
            if (true !== $result) {
                return $this->error($result);
            }
//            if (!in_array($params['roleid'], $this->childrenGroupIds)) {
//                $this->error('没有权限操作！');
//            }
            //密码为空，表示不修改密码
            if (isset($params['password']) && $params['password']) {
                $passwordinfo = encrypt_password($params['password']); //对密码进行处理
                $params['encrypt'] = $passwordinfo['encrypt'];
                $params['password'] = $passwordinfo['password'];

            } else {
                unset($params['password'], $params['encrypt']);
            }
            try {
                $row->allowField(true)->save($params);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success("修改成功！");
        }
        //获取山东省所有市区
        $cityWhere[] = ['pid', '=', 370000];
        $cityWhere[] = ['is_agent', '=', 0];
        $cityList = Db::name('area')
            ->where($cityWhere)
            ->whereOr('id', $row['area_id'])
            ->select();
        foreach ($cityList as $k => $v) {
            $cityList[$v['id']] = $v['name'];
            unset($cityList[$k]);
        }
        $this->assign('cityList', $cityList);
        $this->assign("data", $row);
        return $this->fetch();
    }

    /**
     * 管理员删除
     */
    public function del()
    {
        if (false === $this->request->isPost()) {
            $this->error('未知参数');
        }
        $id = $this->request->param('id/d');
        if (empty($id)) {
            $this->error('请指定需要删除的用户ID！');
        }
        if ($id == 1) {
            $this->error('禁止对超级管理员执行该操作！');
        }
        //分公司账号软删除
        try {
            $admin_info = $this->modelClass->get($id);
            Db::name('area')->where('id', $admin_info['area_id'])->update([
                'id' => $admin_info['area_id'],
                'is_agent' => 0
            ]);
            $this->modelClass->save([
                'is_del' => 1
            ], ['id' => $id]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success("删除成功！");
        $this->error('没有权限删除！');
    }

    //批量更新.
    public function multi()
    {
        // 管理员禁止批量操作
        $this->error();
    }

}
